#include "redstone_repeater.h"


int RS_repeater_init(struct redstone_repeater_stu *repeater){
    if(repeater->pin_init != NULL){
        if(repeater->pin_init(repeater) != 0){
            return -2;
        }
    }else {
        return -1;
    }

    repeater->write_pin(repeater, RP_PIN_OUTPUT_LED, RP_LED_OFF);
    repeater->write_pin(repeater, RP_PIN_OUTPUT, RP_OUT_OFF);
    repeater->write_pin(repeater, RP_PIN_LATCH_LED, RP_LED_OFF);

    return 0;
}

REPEATER_GEAR_E RS_repeater_get_gear(struct redstone_repeater_stu *repeater){
    if(repeater->read_pin(repeater, RP_PIN_GEAR1) == RP_GEAR_SELECTED){
        return RP_GEAR_1;
    }
    if(repeater->read_pin(repeater, RP_PIN_GEAR2) == RP_GEAR_SELECTED){
        return RP_GEAR_2;
    }
    if(repeater->read_pin(repeater, RP_PIN_GEAR3) == RP_GEAR_SELECTED){
        return RP_GEAR_3;
    }
    if(repeater->read_pin(repeater, RP_PIN_GEAR4) == RP_GEAR_SELECTED){
        return RP_GEAR_4;
    }

    return RP_GEAR_UNKNOWN;
}


uint16_t myRS_get_mv_back(struct redstone_stu *rs){
    uint16_t rs_mv = adc_redstone_back*real_Vref*ADC_RS_K;

    return rs_mv;
}

uint16_t myRS_get_mv_left(struct redstone_stu *rs){
    uint16_t rs_mv = adc_redstone_left*real_Vref*ADC_RS_K;

    return rs_mv;
}

uint16_t myRS_get_mv_right(struct redstone_stu *rs){
    uint16_t rs_mv = adc_redstone_right*real_Vref*ADC_RS_K;

    return rs_mv;
}


int myRP_pin_init(struct redstone_repeater_stu *repeater){
    GPIO_InitTypeDef          GPIO_InitStruct;

    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_GPIOB_CLK_ENABLE();

    GPIO_InitStruct.Pin = GPIO_PIN_5 | GPIO_PIN_7;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
    GPIO_InitStruct.Pin = GPIO_PIN_2;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    
    GPIO_InitStruct.Pin = GPIO_PIN_0;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
    GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_3 | GPIO_PIN_4;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    return 0;
}

void myRP_write_pin(struct redstone_repeater_stu *repeater, REPEATER_PIN_E pin, uint8_t state){
    HAL_GPIO_WritePin(repeater->pin_list[pin].port, repeater->pin_list[pin].pin, state);
}

uint8_t myRP_read_pin(struct redstone_repeater_stu *repeater, REPEATER_PIN_E pin){
    return HAL_GPIO_ReadPin(repeater->pin_list[pin].port, repeater->pin_list[pin].pin);
}
